﻿/// <reference path="../../js/utils.js" />
'use strict';

define([
    'screenView',
    'commonModels',

    'backgrid.all',
    'moment',

    'backbone.modelbinder',

    'datepicker',
    'typeahead',
],
function (
    ScreenView,
    CommonModels,
    Backgrid,
    moment
) {
    var View = ScreenView.extend({
        super: null,

        name: 'debtors',
        title: 'Deudores',

        billingHistoryColl: null,
        customersColl: null,
        customersSync: false,

        //events: function() {
        //    return {
        //    };
        //},

        constructor: function () {
            this.super = View.__super__;

            this.billingHistoryColl = new CommonModels.BillingHistoryColl();

            this.customersColl = new CommonModels.CustomerColl();

            this.modelBinder = new Backbone.ModelBinder();
                
            return this.super.constructor.apply(this, arguments);
        },

        //beforeShow: function (routeArgs) {
        //    var that = this;

        //    this.customersColl.fetch({ success: _.bind(this._customersCat_fetch_success, this), });

        //    this.billingHistoryColl.fetch({ success: _.bind(this._billingHistoryColl_fetch_success, this), });

        //    return false;
        //},
        delegateModelEvents: function () {
            this.listenTo(this.model, 'change', this._model_change, this)

            return this.super.delegateModelEvents.apply(this, arguments);
        },
        render: function () {
            this.super.render.apply(this);

            var that = this;

            /* First render actions. */
            if (!this.rendered) {
                var billingHistoryGrid = new Backgrid.Grid({
                    columns: [
                        {
                            name: 'datetime',
                            editable: false,
                            label: 'Fecha Factura',
                            cell: Backgrid.Extension.MomentCenterCell.extend({
                                modelFormat: "YYYY-MM-DD HH:mm:ss.fff",
                                //displayLang: "zh-tw",
                                displayFormat: "dddd DD HH:mm"
                            }),
                        },
                        {
                            name: 'timestamp',
                            editable: false,
                            label: 'Fecha Creación',
                            cell: Backgrid.Extension.MomentCenterCell.extend({
                                modelFormat: "YYYY-MM-DD HH:mm:ss.fff",
                                //displayLang: "zh-tw",
                                displayFormat: "dddd DD HH:mm"
                            }),
                        },
                        {
                            name: 'customer',
                            editable: false,
                            label: 'Cliente',
                            cell: 'string-center',
                        },
                        {
                            name: 'price',
                            editable: false,
                            label: 'Precio',
                            cell: Backgrid.NumberCell.extend({
                                className: 'number-cell currency-text',
                            }),
                        },
                        {
                            name: 'pay',
                            editable: false,
                            label: 'Pago',
                            cell: Backgrid.NumberCell.extend({
                                className: 'number-cell currency-text',
                            }),
                        },
                        {
                            name: 'actions',
                            editable: false,
                            label: '',
                            cell: Backgrid.Extension.ButtonCell.extend({
                                className: 'button-cell action-cell',
                                template: '<button id="detailsBtn" class="btn btn-warning" title="Detalle"><i class="fa fa-list" ></i></button>',
                                events: function () {
                                    return {
                                        'click #detailsBtn': function (e) { that._billingHistory_detailsBtn_click(e, this); },
                                    };
                                },
                            }),
                        },
                        //{
                        //    name: 'delete',
                        //    label: '',
                        //    cell: Backgrid.Extension.DeleteRowCell.extend({
                        //        mustDelete: function () {
                        //            return ($.trim(this.model.get('name')).length != 0);
                        //        },
                        //    }),
                        //},
                    ],
                    collection: this.billingHistoryColl,
                });
                billingHistoryGrid.render();
                // Render the grid and attach the Grid's root to your HTML document
                this.$el.find('#billingHistory').append(billingHistoryGrid.el);


                this.modelBinder.bind(
                    this.model,
                    this.el/*,
                    utils.misc.getModelBindingsFromDOM(
                        this.el,
                        {
                            priceAdjPercentage: [
                                {
                                    selector: '#priceAdjProfitBtn, #priceAdjTotalBtn',
                                    elAttribute: 'disabled',
                                    converter: function (direction, value) {
                                        var valueFix = parseFloat(value);
                                        return (isNaN(valueFix) || value == 0 || value <= -1);
                                    },
                                },
                            ],
                            priceAdjusted: [
                                {
                                    selector: '#adjustPriceBtn, #resetPriceBtn',
                                    elAttribute: 'disabled',
                                    converter: function (direction, value) {
                                        return !value;
                                    },
                                },
                            ],
                        }
                    )*/
                );


                /* Indicates that the view was rendered at least one time. */
                this.rendered = true;
            }
            /* Not first render actions. */
            else {
                
            }


            return this;
        },
        show: function (data) {
            this.customersColl.fetch({ success: _.bind(this._customersCat_fetch_success, this), });

            this.billingHistoryColl.fetch([
                { Name: 'payment', Value: 'pending', },
            ]);

            return this.super.show.apply(this, arguments);
        },
        //triggerReady: function () {
        //    if (this.currentBillLoaded && this.customersSync && this.productsSync)
        //        this.trigger('ready');
        //},

        _billingHistory_detailsBtn_click: function (e, cell) {
            try {
                App.router.navigate(sprintf('facturacion/%d', cell.model.get('id')), { trigger: true, });
            }
            catch (Error) { console.error(Error); }
        },
        _customersCat_fetch_success: function (coll) {
            try {
                var items = [];

                coll.each(function (model) { items.push(model.get('code') + " " + model.get('name')); });

                this.$el.find('#customerTbx').typeahead({
                    source: items,
                    autoSelect: false,
                });


                //this.customersSync = true;

                //this.triggerReady();
            }
            catch (Error) { console.error(Error); }
        },
        _model_change: function (model, options) {
            try {
                var formats = App.config.formats,
                    start = model.get('start'),
                    end = model.get('end'),
                    customerCodeName = model.get('customer');



                this.billingHistoryColl.fetch([
                    { Name: 'start', Value: (start) ? new moment(start, formats.date).format(formats.datetimedb) : null, DbType: 'DateTime', },
                    { Name: 'end', Value: (end) ? new moment(end, formats.date).format(formats.datetimedb) : null, DbType: 'DateTime', },
                    { Name: 'customer', Value: (customerCodeName) ? customerCodeName.split(' ')[0] : '', },
                    { Name: 'payment', Value: 'pending', },
                ]);
            }
            catch (Error) { console.error(Error); }
        },
    });

    return View;
});